package com.example.qixinshangwutong.view.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.qixinshangwutong.BaseApplication;
import com.example.qixinshangwutong.R;
import com.example.qixinshangwutong.model.home.SearchAdapter;
import com.example.qixinshangwutong.model.home.SearchData;
import com.example.qixinshangwutong.model.home.SearchModel;
import com.example.qixinshangwutong.model.home.SearchRequest;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.leancloud.LCObject;
import cn.leancloud.LCQuery;
import cn.leancloud.LCUser;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SearchActivity extends AppCompatActivity {
    private EditText searchText;
    private TextView searchBack;
    private RecyclerView searchHistory;
    private TextView search;

    LCUser currentUser=LCUser.getCurrentUser();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        searchName();
        searchBack();
    }
    private void initView(){
        searchText=findViewById(R.id.edit_select);
        searchBack=findViewById(R.id.text_fanHui);
        searchHistory=findViewById(R.id.list_search_key);
        search=findViewById(R.id.text_search_name);
        LinearLayoutManager llm=new LinearLayoutManager(this);
        searchHistory.setLayoutManager(llm);
        List<SearchModel> list=new ArrayList<>();
        SearchAdapter adapter=new SearchAdapter(SearchActivity.this);
        adapter.setData(list);
        searchHistory.setAdapter(adapter);
        if (currentUser!=null){
            LCQuery<LCObject> query=new LCQuery<>("admin");
            query.whereEqualTo("id",currentUser.getObjectId());
            query.findInBackground().subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<LCObject>>() {
                        @Override
                        public void onSubscribe(@NotNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NotNull List<LCObject> lcObjects) {
                            Toast.makeText(SearchActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
                            for (int i = 0; i < lcObjects.size(); i++) {
                                SearchModel model=new SearchModel();
                                model.setKey(lcObjects.get(i).get("key").toString());
                                list.add(model);
                                
                            }
                            adapter.notifyDataSetChanged();

                        }

                        @Override
                        public void onError(@NotNull Throwable e) {
                            Toast.makeText(SearchActivity.this,"添加失败",Toast.LENGTH_SHORT).show();

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }



    }
   /* private void editSearch(){
        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String key=searchText.getText().toString();
                if (!key.isEmpty()){
                    search(key);
                    if (currentUser!=null){
                        addHistory(key);
                    }
                }else{
                    Toast.makeText(SearchActivity.this, "请输入需要搜索的内容", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });

    }*/
    private void search(String key){
        Call<SearchRequest<SearchData>> call= BaseApplication.api.getSearch(key);
        call.enqueue(new Callback<SearchRequest<SearchData>>() {
            @Override
            public void onResponse(Call<SearchRequest<SearchData>> call, Response<SearchRequest<SearchData>> response) {
                String url=response.body().getValues().getRedirect_shareurl();
                if (!url.isEmpty()){
                    Intent intent=new Intent(SearchActivity.this,CompanyActivity.class);
                    intent.putExtra("url",url);
                    intent.putExtra("name",response.body().getValues().getRedirect_title());
                    startActivity(intent);
                }else{
                    Toast.makeText(SearchActivity.this,"未查询到相关数据",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<SearchRequest<SearchData>> call, Throwable t) {

            }
        });
    }
    private void addHistory(String key){
        LCObject object=new LCObject("admin");
        object.put("key",key);
        object.put("id",currentUser.getObjectId());
        object.saveInBackground()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LCObject>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull LCObject lcObject) {
                        Toast.makeText(SearchActivity.this,"添加到历史搜索",Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        Toast.makeText(SearchActivity.this,"添加失败",Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
    private void searchBack(){
        searchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchActivity.this.finish();
            }
        });
    }
    private void searchName(){
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key=searchText.getText().toString();
                if (!key.isEmpty()){
                    search(key);
                    addHistory(key);

                }else{
                    Toast.makeText(SearchActivity.this, "请输入需要搜索的内容", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}